package com.duojuhe.admin.spring.webconfig;

import com.duojuhe.common.constant.ApiPathConstants;
import com.duojuhe.interceptor.MyWebInterceptor;
import com.duojuhe.common.config.FileUploadConfig;
import com.duojuhe.interceptor.SecurityInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.io.File;

/**
 * <br>
 * <b>功能：</b>MVC配置<br>
 * 例如：public/file/** -> 磁盘某个位置<br>
 * 例如：拦截器<br>
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private static final String FILE_START = "file:";
    @Resource
    private FileUploadConfig fileUploadConfig;
    @Resource
    private MyWebInterceptor myWebInterceptor;
    @Resource
    private SecurityInterceptor refererInterceptor;

    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 要以文件分隔符结尾
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/META-INF/resources/",
                "classpath:/resources/",
                "classpath:/webjars/",
                "classpath:/public/",
                "classpath:/file/",
                getFileLocation(fileUploadConfig.getWebsiteRootPath())
        );
        registry.addResourceHandler(fileUploadConfig.getFileUrlPrefix() + "/**").addResourceLocations(getFileLocation(fileUploadConfig.getRootPath()));
    }

    /**
     * 拦截器配置 支持 多个拦截器组成一个拦截器链
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 系统安全基础拦截
        registry.addInterceptor(myWebInterceptor).addPathPatterns("/**");
        // 需要校验请求来源的路径拦截
        registry.addInterceptor(refererInterceptor).addPathPatterns("/"+ApiPathConstants.ADMIN_PATH + "/**", "/adminLogin");
    }


    /**
     * 获取路径
     *
     * @param rootPath
     * @return
     */
    private String getFileLocation(String rootPath) {
        String fileUploadLocation = FILE_START + rootPath;
        if (!fileUploadLocation.endsWith(File.separator)) {
            fileUploadLocation = fileUploadLocation + File.separator;
        }
        return fileUploadLocation;
    }


}
